<?php

namespace App\Console\Commands;

use App\Models\SettlementList;
use App\Models\SettlementListInfo;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SettlementDay extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'settlementDay';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'settlementDay';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            $status = '1';
            $SetlementDayDetails = \App\Models\SettlementDay::where('status', '=', $status)
                ->select('user_id', 'source_type', 'rate', 'config_id', 'name')
                ->get();
            if($SetlementDayDetails){
                foreach ($SetlementDayDetails as $key => $val){
                    $user_name = $val['name'];
                    $user_id = $val['user_id'];
                    $source_type = $val['source_type'];
                    $config_id = $val['config_id'];
                    $rate = $val['rate'];
                    $source_type_desc = $val['source_type'];
                    $s_no = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)) . $config_id . $user_id . $source_type;
                    $dx = 1;
                    $dx_desc = "服务商";
                    if ($user_name && $user_name != "NULL") {
                        $dx_desc = $user_name.'-服务商';
                    }
                    $begin_time=strtotime(date("Y-m-d",time()));
                    $time_start = date('Y-m-d 00:00:00',$begin_time);
                    $time_end = date('Y-m-d 00:00:00',$begin_time+60*60*24);

                    if (env('DB_D1_HOST')) {
                        $settlement_lists = DB::connection("mysql_d1")->table("settlement_lists");
                    } else {
                        $settlement_lists = DB::table('settlement_lists');
                    }

                    //如果有未结算的记录 不允许结算
                    $SettlementList = $settlement_lists->where('is_true', 0)
                        ->where('config_id', $config_id)
                        ->where('source_type', $source_type)
                        ->where('dx_id', $user_id)
                        ->where('dx', $dx)
                        ->select('id')
                        ->first();
                    if ($SettlementList) {
                        continue;
                    }

                    //查出当天返佣未结算用户列表
                    $where = [];
                    $where[] = ['settlement', '02'];
                    $where[] = ['money', '!=', '0.0000'];
                    if ($source_type) {
                        $where[] = ['source_type', $source_type];
                    }
                    if ($time_start) {
                        $where[] = ['created_at', '>=', $time_start];
                    }
                    if ($time_end) {
                        $where[] = ['created_at', '<=', $time_end];
                    }


//                $table = 'user_wallet_details' . '_' . $day;
//                if (env('DB_D1_HOST')) {
//                    if (Schema::hasTable($table)) {
//                        $UserWalletDetail = DB::connection("mysql_d1")->table($table);
//                    } else {
//                        $UserWalletDetail = DB::connection("mysql_d1")->table("user_wallet_details");
//                    }
//                } else {
//                    if (Schema::hasTable($table)) {
//                        $UserWalletDetail = DB::table($table);
//                    } else {
//                        $UserWalletDetail = DB::table('user_wallet_details');
//                    }
//                }
                    $UserWalletDetail = DB::table('user_wallet_details');
                    //选择某个服务商
                    if ($user_id && $user_id != "NULL") {
                        $user_ids = $this->getSubIds($user_id);
                        $users_obj = $UserWalletDetail->where($where)
                            ->whereIn('user_id', $user_ids)
                            ->select('user_id')
                            ->distinct('user_id')//去重
                            ->get();
                    } else {
                        $users_obj = $UserWalletDetail->where($where)
                            ->select('user_id')
                            ->distinct('user_id')//去重
                            ->get();
                    }
                    //没有找到结算记录
                    if ($users_obj->isEmpty()) {
                        continue;
                    }

                    //开启事务
                    try {
                        DB::beginTransaction();
                        $total_amount = 0;
                        $total_get_amount = 0;
                        //整个大的平台
                        $insert1 = [
                            'config_id' => $config_id,
                            's_no' => $s_no,
                            'dx' => $dx,
                            'dx_desc' => $dx_desc,
                            's_time' => $time_start,
                            'e_time' => $time_end,
                            'source_type' => $source_type,
                            'source_type_desc' => $source_type_desc,
                            'total_amount' => $total_amount,
                            'get_amount' => $total_get_amount,
                            'rate' => $rate,
                            'is_true' => 0,
                            'dx_id' => isset($user_id) ? $user_id : "",
                        ];
                        $SettlementList = SettlementList::create($insert1);
                        $settlement_list_id = $SettlementList->id;

                        foreach ($users_obj as $k => $v) {
                            $user_id = $v->user_id;
//                        $table = 'user_wallet_details' . '_' . $day;
//                        if (env('DB_D1_HOST')) {
//                            if (Schema::hasTable($table)) {
//                                $UserWalletDetail1 = DB::connection("mysql_d1")->table($table);
//                            } else {
//                                $UserWalletDetail1 = DB::connection("mysql_d1")->table("user_wallet_details");
//                            }
//                        } else {
//                            if (Schema::hasTable($table)) {
//                                $UserWalletDetail1 = DB::table($table);
//                            } else {
//                                $UserWalletDetail1 = DB::table('user_wallet_details');
//                            }
//                        }
                            $UserWalletDetail1 = DB::table('user_wallet_details');

                            $UserWalletDetail1 = $UserWalletDetail1->where('source_type', $source_type)
                                ->where('created_at', '>', $time_start)
                                ->where('created_at', '<', $time_end)
                                ->where('settlement', '02')
                                ->where('user_id', $v->user_id)
                                ->select('money');
                            $money = $UserWalletDetail1->sum('money');
                            //总金额
                            $total_amount = $total_amount + $money;
                            $j = number_format($rate / 100, 4, '.', '');
                            $get_amount = $money - (($money * $j));
                            $get_amount = number_format($get_amount, 4, '.', '');
                            $total_get_amount = $total_get_amount + $get_amount;
                            //个人金额
                            $insert = [
                                's_no' => $s_no,
                                'config_id' => $config_id,
                                'dx' => $dx,
                                's_time' => $time_start,
                                'e_time' => $time_end,
                                'source_type' => $source_type,
                                'source_type_desc' => $source_type_desc,
                                'total_amount' => $money,
                                'get_amount' => $get_amount,
                                'user_id' => $user_id,
                                'is_true' => 0,
                                'rate' => $rate,
                                'settlement_list_id' => $settlement_list_id
                            ];
                            SettlementListInfo::create($insert);
                        }

                        SettlementList::where('id', $settlement_list_id)->update([
                            'get_amount' => $total_get_amount,
                            'total_amount' => $total_amount,
                            's_time' => $time_start,
                            'e_time' => $time_end,
                        ]);
                        DB::commit();
                    } catch (\Exception $e) {
                        Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
                        DB::rollBack();
                        return json_encode([
                            'status' => '2',
                            'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()
                        ]);
                    }

                }
            }
        } catch (\Exception $exception) {
            Log::info('服务商定时任务error');
            Log::info($exception->getMessage().' | '.$exception->getFile().' | '.$exception->getLine());
        }
    }

    function getSubIds($userID, $includeSelf = true, $t1 = "", $t2 = "")
    {
        $userIDs = [$userID];
        $where = [];

        if ($t2 == "") {
            $t2 = date('Y-m-d H:i:s', time());

        }

        if ($t1) {
            $where[] = ['created_at', '>=', $t1];
            $where[] = ['created_at', '<=', $t2];

        }
        while (true) {
            //不允许设置读
            $subIDs = User::whereIn('pid', $userIDs)
                ->where($where)
                ->select('id')->get()
                ->toArray();
            $subIDs = array_column($subIDs, 'id');
            $userCount = count($userIDs);
            $userIDs = array_unique(array_merge($userIDs, $subIDs));
            if ($userCount == count($userIDs)) {
                break;
            }
        }
        if (!$includeSelf) {
            for ($i = 0; $i < count($userIDs); ++$i) {
                if ($userIDs[$i] == $userID) {
                    array_splice($userIDs, $i, 1);
                    break;
                }
            }
        }
        return $userIDs;
    }
}
